#include "scores.h"

void writeScores(Score* scores, int count){
	FILE *fd;
	int i;
	fd = fopen("scores.txt","w");
	for(i=0;i<count;++i){
		fprintf(fd,"%d %s\n",scores[i].score,scores[i].name);
	}
	fclose(fd);
}

int importScoresFile(Score *scores){
	int k = 0;
	FILE *fd;
	
	fd = fopen("scores.txt","r");
	while (!feof(fd) && k<5) {
		if (fscanf(fd, "%d %s", &scores[k].score, scores[k].name) != 2)
            break;
        k++;
    }
    fclose(fd);
    
    return k;
}

void scoreboard(){
	extern ConfigInfo conf;
	extern int last_sc;
	extern Queue keys_queue;
	int count;
	int i;
	Score scores[5];
	count = importScoresFile(scores);
	qsort(scores,count,sizeof(Score),score_cmp);
	conf.video_base = enter_graphics(0x103,&(conf.map));
	
	drawStringAt("Highscores", HRES/2-5*8*8, 25, 15, 0, 8, conf.video_base, conf.table);
	for(i=0;i<count;++i){
		drawIntAt	(scores[i].score, 	HRES/2 - 200, 	150+i*16*4 +10, 15 ,0, 4, conf.video_base,conf.table);
		drawStringAt(scores[i].name, 	HRES/2, 		150+i*16*4 +10, 15, 0, 4, conf.video_base, conf.table);
	}
	
	
	do{
		if(!queueEmpty(&keys_queue))
		{
			last_sc = queueGet(&keys_queue);
		}
	}
	while(last_sc!=1);
}

int score_cmp (const void *sc1, const void *sc2){
  return (((Score*)sc1)->score < ((Score*)sc2)->score);
}
